package com.shadt.core.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shadt.core.dao.ResourceDao;
import com.shadt.core.dao.ResourceTypeDao;
import com.shadt.core.dao.RoleDao;
import com.shadt.core.entity.Resource;
import com.shadt.core.entity.ResourceType;
import com.shadt.core.entity.Role;
import com.shadt.core.model.Tree;
import com.shadt.core.service.ResourceService;
import com.shadt.core.util.SessionInfo;
import com.shadt.core.vo.ResourceVo;

/**
 * 资源栏目业务层实现类
 * 
 * @author SongR
 * 
 */
@Service
public class ResourceServiceImpl implements ResourceService {
	@Autowired
	ResourceDao resourceDao;
	@Autowired
	ResourceTypeDao resourceTypeDao;
	@Autowired
	RoleDao roleDao;

	/**
	 * 实现根据用户获取资源栏目信息
	 */
	public List<Tree> getByUser(SessionInfo sessionInfo) {
		List<Resource> l = null;
		List<Tree> lt = new ArrayList<Tree>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("resourceTypeId", "0");// 资源类型为菜单
		if (null != sessionInfo) {
			params.put("userId", sessionInfo.getId());// 查看自己有权限的资源
			l = resourceDao
					.find("select distinct t from Resource t join fetch t.resourceType type join fetch t.roles role join role.users user where type.id = :resourceTypeId and user.id = :userId order by t.seq",
							params);
		} else {
			l = resourceDao
					.find("select distinct t from Resource t join fetch t.resourceType type where type.id = :resourceTypeId order by t.seq",
							params);
		}

		if (null != l && l.size() > 0) {
			for (Resource r : l) {
				Tree tree = new Tree();
				BeanUtils.copyProperties(r, tree);
				if (r.getResource() != null) {
					tree.setPid(r.getResource().getId());
				}
				tree.setText(r.getName());
				tree.setIconCls(r.getIcon());

				// 设置借点url属性
				Map<String, Object> attr = new HashMap<String, Object>();
				attr.put("url", r.getUrl());
				tree.setAttributes(attr);
				//
				lt.add(tree);
			}
		}
		return lt;
	}

	/**
	 * 实现添加资源
	 */
	public void addResource(ResourceVo resourceVo) {
		Resource resource = new Resource();
		if (null != resourceVo) {
			resource.setId(UUID.randomUUID().toString());
			resource.setName(resourceVo.getName());
			resource.setRemark(resourceVo.getRemark());
			resource.setIcon(resourceVo.getIcon());
			if (null != resourceVo.getSeq())
				resource.setSeq(Integer
						.parseInt(resourceVo.getSeq().toString()));
			resource.setUrl(resourceVo.getUrl());
			resource.setResourceType(resourceTypeDao.get(ResourceType.class,
					resourceVo.getResourceTypeId()));
			resourceDao.saveOrUpdate(resource);
		}
	}

	/**
	 * 实现按条件查询所有资源
	 */
	public List<ResourceVo> getAllResource(String sSearch, int pageNo,
			int rows, String resourceTypeId) {
		List<ResourceVo> ul = new ArrayList<ResourceVo>();
		String hql = " from Resource t ";
		List<Resource> l = resourceDao.find(
				hql + whereHql(resourceTypeId, sSearch), pageNo / rows + 1,
				rows);
		if (null != l && l.size() > 0) {
			for (Resource t : l) {
				ResourceVo u = new ResourceVo();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		return ul;
	}

	/**
	 * 实现根据条件获取记录总数
	 */
	public Long getResourceCount(String resourceTypeId, String sSearch) {
		return resourceDao.count("select count(*) from Resource t"
				+ whereHql(resourceTypeId, sSearch));
	}

	/**
	 * 实现删除资源信息
	 */
	public void delResource(String id) {
		resourceDao.delete(resourceDao.get(Resource.class, id));
	}

	/**
	 * 实现获取所有资源添加到授权列表
	 */
	public List<ResourceVo> getAllResourceToEmpower(String resourceTypeId,
			String id) {
		List<ResourceVo> resourceVoList = new ArrayList<ResourceVo>();
 		List<Resource> resourceList = resourceDao
				.find("from Resource where resourceType.id='" + resourceTypeId
						+ "' order by seq");
		for (Resource resource : resourceList) {
			ResourceVo resourceVo = new ResourceVo();
			resourceVo.setId(resource.getId());
			resourceVo.setName(resource.getName());
			for(Role role : resource.getRoles()){
				if(role.getId().equals(id)){
					resourceVo.setCheck(true);
				}
			}
			resourceVoList.add(resourceVo);
		}
		return resourceVoList;
	}
	/**
	 * 实现资源授权
	 */
	public void addResourceToEmpower(String resourceIds, String roleId) {
		Role role = roleDao.get(Role.class,roleId);
		Set<Resource> rSet = new HashSet<Resource>();
		if(null!=resourceIds &&resourceIds.length()>0&&!resourceIds.equals("null")){
			for (String id : resourceIds.split(",")) {
				rSet.add(resourceDao.get(Resource.class, id));
			}
		}
		role.setResources(rSet);
		roleDao.saveOrUpdate(role);
//		User user = userDao.get(User.class, userId);
//		Set<Role> rSet = new HashSet<Role>();
//		if (null != roleIds && roleIds.length() > 0 && !roleIds.equals("null")) {
//			for (String id : roleIds.split(",")) {
//				rSet.add(roleDao.get(Role.class, id));
//			}
//		}
//		user.setRoles(rSet);
//		userDao.save(user);
	}
	/**
	 * 组装where条件
	 * 
	 * @param user
	 * @param params
	 * @return
	 */
	private String whereHql(String resourceTypeId, String str) {
		String hql = " where t.resourceType.id= '" + resourceTypeId + "' ";
		if (null != str && !"".equals(str)) {
			hql += " and  t.name like   '%" + str + "%' ";
		}
		return hql;
	}
}
